<template>
	<view>
		<nav-bar fontColor="#FFFFFF" title="融资申请"></nav-bar>
		<!-- <view class="topStep">
			<uni-steps :options="list1" :active="active1" />
		</view> -->
		<view class="topStep">
			<uni-steps style="padding-top: 40rpx;" :options="list1" :active="active1" />
			<view style="display: flex;justify-content: space-around;">
				<view class="numberBox">
					<view class="numBox">
						<span style="color: #f62105;font-size: 40rpx;font-weight: bold;">{{ creditInfor.credit }}</span>
						<span style="color: #f62105;font-size: 25rpx;margin-top: 18rpx;">元</span>
					</view>
					<view style="font-size: 25rpx;">授信额度</view>
				</view>
				<view class="colorBar"></view>
				<view class="numberBox">
					<view class="numBox">
						<span
							style="color: #f62105;font-size: 40rpx;font-weight: bold;">{{ creditInfor.credit - creditInfor.creditLeft }}</span>
						<span style="color: #f62105;font-size: 25rpx;margin-top: 18rpx;">元</span>
					</view>
					<view style="font-size: 25rpx;">已用额度</view>
				</view>
				<view class="colorBar"></view>
				<view class="numberBox">
					<view class="numBox">
						<span
							style="color: #f62105;font-size: 40rpx;font-weight: bold;">{{ creditInfor.creditLeft }}</span>
						<span style="color: #f62105;font-size: 25rpx;margin-top: 18rpx;">元</span>
					</view>
					<view style="font-size: 25rpx;">可用额度</view>
				</view>
			</view>
			<!-- <view style="display: flex;justify-content: space-around;">
				<view class="numberBox">
					<view class="numBox">
						<span style="color: #f62105;font-size: 40rpx;font-weight: bold;">46,568,54</span>
						<span style="color: #f62105;font-size: 25rpx;margin-top: 18rpx;">元</span>
					</view>
					<view style="font-size: 25rpx;">已用额度</view>
				</view>
				<view class="colorBar"></view>
				<view class="numberBox">
					<view class="numBox">
						<span
							style="color: #f62105;font-size: 40rpx;font-weight: bold;">{{ creditInfor.frezeCredit }}</span>
						<span style="color: #f62105;font-size: 25rpx;margin-top: 18rpx;">元</span>
					</view>
					<view style="font-size: 25rpx;">冻结额度</view>
				</view>
			</view> -->
		</view>
		<uni-group mode="card">
			<qiun-title-bar title="交易凭证" />
			<view style="height: 60rpx;">
				<view style="float: left;font-size: 32rpx;">当前订单总额：{{baseFormData.amount}}元</view>
				<view style="float: right;font-size: 32rpx;color: #afafaf;">{{fileList.length}}/1</view>
			</view>
			<view style="height: 80rpx;">
				<button @tap="nextStep" type="primary" size="mini"
					:disabled="baseFormData.salesOrderNo != ''">添加</button>
			</view>

			<view v-for="(item,index) in fileList"
				style="height: 60rpx;width: 100%;margin-top: 10rpx;border: 1px solid #EEEEEE;">
				<view style="float: left;line-height: 60rpx;padding-left: 20rpx;">
					{{JSON.parse(item.products)[0].product_name}}
				</view>
				<view @click="removeFile(index)" style="float: right;margin:15rpx 10rpx;">
					X
				</view>
			</view>
		</uni-group>
		<view class="example">
			<!-- 基础用法，不包含校验规则 -->
			<!-- 合同里面的 -->
			<!-- <view @click="chooseOrder"
				style="padding: 20rpx;font-size: 28rpx;color: #0055ff;letter-spacing: 3rpx;font-weight: bold;">
				选择</view> -->
			<uni-forms ref="baseForm" :model="baseFormData" labelWidth="80px" labelPosition="left">
				<uni-forms-item required label="订单号">
					<uni-easyinput :disabled="true" v-model="baseFormData.salesOrderNo" />
				</uni-forms-item>
				<!-- <uni-forms-item required label="合同">
					<view style="display: flex;">
						<uni-easyinput v-model="baseFormData.salesOrderNo" :disabled="true" placeholder="请输入订单或合同编号" />
					</view>
				</uni-forms-item> -->
				<!-- <uni-forms-item required label="企业">
					<uni-data-select @change="supplierChange" :localdata="supplierList" v-model="baseFormData.salerNo"
						placeholder="请选择收款企业">
					</uni-data-select>
				</uni-forms-item> -->
				<uni-forms-item required label="产品">
					<uni-data-select :disabled="true" @change="finLoanProductChange" :localdata="finLoanProductList"
						v-model="baseFormData.productNo" placeholder="请选择融资产品">
					</uni-data-select>
				</uni-forms-item>
				<uni-forms-item label="金额" required>
					<view style="display: flex;">
						<!-- <uni-easyinput :disabled="true" style="width: 35%;" v-model="baseFormData.amount"
							placeholder="请输入融资金额" /> -->
						<view
							style="padding: 20rpx;font-size: 28rpx;color: #000000;letter-spacing: 3rpx;font-weight: bold;">
							{{baseFormData.amount}}
							<view style="position: absolute;right: 20rpx;top: 20rpx;">元</view>
						</view>
					</view>
				</uni-forms-item>
				<!-- <uni-forms-item label="月息" required>
					<view style="display: flex;">
						<uni-easyinput :disabled="true" style="width: 35%;" v-model="baseFormData.interestRate"
							placeholder="请输入融资月息" />
						<view
							style="padding: 20rpx;font-size: 28rpx;color: #000000;letter-spacing: 3rpx;font-weight: bold;">
							{{baseFormData.interestRate}}%
						</view>
					</view>
				</uni-forms-item> -->
				<!-- <uni-forms-item label="期数" required>
					<view style="display: flex;">
						<uni-data-select :localdata="qishuList" v-model="baseFormData.paymentTimes"
							placeholder="请选择还款期数">
						</uni-data-select>
						<view
							style="padding: 20rpx;font-size: 28rpx;color: #000000;letter-spacing: 3rpx;font-weight: bold;">
							{{baseFormData.paymentTimes}}期
						</view>
					</view>
				</uni-forms-item> -->
				<!-- <uni-forms-item required label="类型">
					<uni-data-select :localdata="leixingList" v-model="baseFormData.paymentType" placeholder="请选择还款类型">
					</uni-data-select>
					<uni-easyinput v-model="baseFormData.paymentType" placeholder="请输入还款类型" />
				</uni-forms-item> -->
				<!-- <uni-forms-item required label="用款日">
					<uni-datetime-picker v-model="baseFormData.openDate"
						placeholder="请选择预计用款日"></uni-datetime-picker>
				</uni-forms-item>
				<uni-forms-item required label="到期日">
					<uni-datetime-picker v-model="baseFormData.validatedTo"
						placeholder="请选择到期日"></uni-datetime-picker>
				</uni-forms-item>
				<uni-forms-item required label="发票">
					<uni-easyinput v-model="baseFormData.invoiceNo" placeholder="请输入发票" />
				</uni-forms-item> -->
				<!-- <uni-forms-item required label="备注">
					<uni-easyinput type="textarea" v-model="baseFormData.remark" placeholder="备注" />
				</uni-forms-item> -->
			</uni-forms>
		</view>

		<view style="height: 120rpx;">
			<view class="bottomBox">
				<view class="buttonBox" @tap="submit">
					<button class="button_fix" size="default">提交</button>
				</view>
			</view>
		</view>
		<l-file ref="lFile" :logo="logo" @up-success="onSuccess"></l-file>
		<uni-popup ref="inputDialog" type="dialog">
			<uni-popup-dialog title="订单选择" ref="inputClose" @confirm="salesOrderItemConfirm" mode="chooseOrder">
			</uni-popup-dialog>
		</uni-popup>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				fileList: [],
				logo: 'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fbpic.588ku.com%2Felement_origin_min_pic%2F00%2F00%2F07%2F155788a6d8a5c42.jpg&refer=http%3A%2F%2Fbpic.588ku.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1619847627&t=2da40b583002205c204d980b54b35040',
				active1: 0,
				list1: [{
					title: '填写需求'
				}, {
					title: '融资确认'
				}, {
					title: '缴纳费用'
				}, {
					title: '业务审批'
				}, {
					title: '审批成功'
				}],
				baseFormData: {
					salerNo: uni.getStorageSync('userInfo').customerId, //收款企业号
					salerName: '', //收款企业
					receiverName: '',
					baoliCompany: '',
					receiverNo: '',
					amount: 0, //融资金额
					productName: '', //融资产品名
					productNo: '', //融资产品号
					qty: '',
					unit: '',
					openDate: '', //预期用款日
					validatedTo: '', //到期日
					paymentType: '', //还款类型
					paymentTimes: '', //还款期数
					interestRate: '', //融资月息
					salesOrderNo: '', //合同号
					creditBillNo: '', //融资单号
					basicNo: '',
					invoiceNo: '', //发票号码
					remark: ''
				},
				creditInfor: {
					credit: '',
					custType: '',
					creditLeft: '',
					frezeCredit: ''
				},
				active1: 0,
				supplierList: [],
				customerSearchList: [],
				salesOrderItemList: [],
				finLoanProductList: [],
				qishuList: [{
						text: '一个月',
						value: 1
					},
					{
						text: '三个月',
						value: 3
					},
					{
						text: '六个月',
						value: 6
					},
					{
						text: '十二个月',
						value: 12
					}
				],
				leixingList: [{
						text: '等额本金',
						value: '等额本金',
					},
					{
						text: '等额本息',
						value: '等额本息',
					},
					{
						text: '先息后本',
						value: '先息后本',
					}
				]
			}
		},
		onLoad(e) {
			uni.$on('confirmOrder', res => {
				this.fileList = []
				this.fileList = res
				this.baseFormData.salesOrderNo = res[0].order_id
				this.baseFormData.amount = res[0].pay_amount
			})
			if (e) {
				let formData = JSON.parse(e.id)
				console.log(formData)
				this.baseFormData.productName = formData.finLoanProduct.productName
				this.baseFormData.productNo = formData.finLoanProduct.id
				console.log(this.baseFormData)
			}
			this.supplierSearch(); //收款企业
			this.finLoanProductSearch(); //融资产品
			// this.getMyCustInfor(); //获取个人额度
			this.getCustInfor();
			// this.salesOrderItemSearch(); //订单或合同编号
		},
		methods: {
			nextStep() {
				uni.navigateTo({
					url: '/pages/limit/financing-nextStep'
				})
			},
			removeFile(e) {
				console.log(e)
				this.fileList.splice(e, 1)
				this.baseFormData.salesOrderNo = ''
				this.baseFormData.amount = ''
				console.log(this.fileList)
			},
			onUpload() {
				if (this.fileList.length > 4) {
					this.messageToggle('error', '最多只能上传5个文件')
					return
				}
				/**
				 * currentWebview: 当前webview
				 * url：上传接口地址
				 * name：附件key,服务端根据key值获取文件流，默认file,上传文件的key
				 * header: 上传接口请求头
				 */
				console.log('--------------------');
				this.$refs.lFile.upload({
					// #ifdef APP-PLUS
					//（app端必传）nvue页面使用时请查阅nvue获取当前webview的api，当前示例为vue窗口
					currentWebview: this.$mp.page.$getAppWebview(),
					// #endif
					//替换为你的上传接口地址
					url: 'http://115.29.199.1:18527/web/tbWmsMaterialDeliveryLine/importData',
					// 服务端接收附件的key
					name: 'file',
					//根据你接口需求自定义 (优先不传content-type,安卓端无法收到参数再传)
					header: {
						// "Content-Type": "application/json; charset=UTF-8",
						'Authorization': 'Bearer ' + uni.getStorageSync('token'),
					},

					// 限制选择附件的大小上限，默认10M
					// maxSize: 20,

					// 若需要在body单独添加附件名或附件大小如下方式传入组件：
					// addName: '后端要的附件名称字段key,此处请勿写name的同值如(file)，会覆盖name',
					// addSize: '后端要的附件大小字段key'

					// body参数直接写key,value,如：
					// date: '2020-1-1',
					// key2: 'value2',
				});
			},
			chooseOrder() {
				this.$refs.inputDialog.open();
			},
			salesOrderItemConfirm(e) {
				console.log(e)
				this.baseFormData.salesOrderNo = e[0].salesOrderNo
				this.baseFormData.amount = e[0].custRelSalesPrice
				this.baseFormData.productName = e[0].skuName
				//    this.form.productNo =contract.custSkuId
				this.baseFormData.unit = e[0].unit
				this.baseFormData.qty = e[0].qty
				this.baseFormData.basicNo = e[0].id
				this.baseFormData.salerNo = e[0].supplierNo
				this.finLoanProductChange(this.baseFormData.productNo)

			},
			supplierSearch() {
				let opt = {
					url: 'basic/supplier/search',
					method: 'POST'
				};
				this.$http.httpTokenRequest(opt, {}).then(res => {
					for (let i in res.data.data) {
						this.supplierList.push({
							text: res.data.data[i].supplierName,
							value: res.data.data[i].id
						})
					}
				})

			},
			supplierChange(e) {
				for (let i in this.supplierList) {
					if (e == this.supplierList[i].id) {
						this.baseFormData.supplierName = this.supplierList[i].supplierName
					}
				}
			},
			finLoanProductSearch() {
				let opt = {
					url: 'loanProduct/finLoanProduct/search',
					method: 'POST'
				};
				this.$http.httpTokenRequest(opt, {}).then(res => {
					for (let i in res.data.data) {
						this.finLoanProductList.push({
							text: res.data.data[i].productName,
							value: res.data.data[i].id
						})
					}
				})
			},
			finLoanProductChange(e) {
				let opt = {
					url: 'loanProduct/finLoanProduct/' + e,
					method: 'GET'
				};
				this.$http.httpTokenRequest(opt).then(res => {
					this.baseFormData.interestRate = res.data.data.montlyRate
					this.baseFormData.paymentTimes = res.data.data.paybackNumbers
					this.baseFormData.paymentType = res.data.data.paymentType
				})
			},
			getCustInfor() {
				let that = this;
				let opt = {
					url: 'finance/customerCredit/getCustInfor',
					method: 'POST'
				};
				let params = {
					CustomerNo: uni.getStorageSync('userInfo').customerId,
					FinProductNo: this.baseFormData.productNo
				};
				this.$http.httpTokenRequest(opt, params).then(res => {
					that.creditInfor.creditLeft = res.data.data.remainLimit
					that.creditInfor.credit = res.data.data.preCreditLimit
				})
			},
			getMyCustInfor() {
				let that = this;
				let opt = {
					url: 'basic/customer/getMyCustInfor',
					method: 'POST'
				};
				this.$http.httpTokenRequest(opt, {}).then(res => {
					that.creditInfor.custType = res.data.data.custType
					// that.creditInfor.creditLeft = res.data.data.creditLeft
					// that.creditInfor.credit = res.data.data.credit
					that.creditInfor.frezeCredit = res.data.data.frezeCredit
					that.baseFormData.receiverName = res.data.data.customerName
					// that.baseFormData.creditBillNo = res.data.data.remark
					that.baseFormData.baoliCompany = res.data.data.baoliCompanyName
				})
			},
			salesOrderItemSearch() {
				let opt = {
					url: 'order/salesOrderItem/search',
					method: 'POST'
				};
				this.$http.httpTokenRequest(opt, {}).then(res => {
					this.salesOrderItemList = res.data.data
				})
			},
			submit() {
				// uni.getStorageSync('WXUserToken').openid
				// let opt = {
				// 	url: 'yeepay/prePay/wxGzh/' + this.baseFormData.salesOrderNo + '/' + 'oMJ4X6HnDNLBc8npfbqbV3DoUzLM',
				// 	method: 'POST'
				// };
				// this.$http.httpTokenRequest(opt, {}).then(res => {
				// 	console.log(res)
				// 	res = JSON.parse(res.data.data)
				// 	console.log(res.appId)
				// })
				if (this.baseFormData.salesOrderNo != '') {
					const self = this;
					// 微信支付
					let ua = navigator.userAgent.toLowerCase();
					console.log(ua)
					//判断当前是否为微信浏览器
					if (ua.match(/MicroMessenger/i) == "micromessenger") {
						// 是微信浏览器
						// 使用微信支付
						let opt = {
							url: 'yeepay/prePay/wxGzh/' + this.baseFormData.salesOrderNo + '/' + uni.getStorageSync(
								'WXUserToken').openid,
							method: 'POST'
						};
						// uni.setStorageSync('baseFormData',this.baseFormData)
						this.$http.httpTokenRequest(opt, {}).then(res => {
							if (res.data.code == 200) {
								let response = JSON.parse(res.data.data)
								this.financingApply();
								console.log(response.appId)
								this.$wx.config({ //全局参数配置
									debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
									appId: response.appId, // 必填，公众号的唯一标识
									timestamp: response.timeStamp, // 必填，生成签名的时间戳
									nonceStr: response.nonceStr, // 必填，生成签名的随机串
									signature: response.paySign, // 必填，签名，见附录1
									jsApiList: ['chooseWXPay'] // 必填
								});
								this.$wx.ready(function() { //预请求，看能否发起微信支付
									self.$wx.checkJsApi({ //判断当前版本是否支持指定js接口
										jsApiList: ['chooseWXPay'], // 需要检测的JS接口列表
										success: function(res) {
											console.log('成功信息1');
											console.log(res);
										},
										fail: function(res) {
											console.log('失败信息1');
											console.log(res);
										}
									});

									self.$wx.chooseWXPay({ //发起一个微信的支付请求
										timestamp: response.timeStamp, // 支付签名时间戳
										nonceStr: response.nonceStr, // 支付签名随机串，不长于 32 位
										package: response
										.package, // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=***）
										signType: response
										.signType, // 签名方式，默认为'SHA1'，使用新版支付需传入'MD5'
										paySign: response.paySign, // 支付签名,与签名是一个东西
										success: async function(res) {
											await console.log(res, "成功信息2");
											uni.showToast({
												title: '支付成功'
											})

										},
										cancel: function(res) {
											// uni.removeStorageSync('baseFormData')
											uni.showToast({
												title: '支付取消'
											})
										},
										fail: function(res) {
											// uni.removeStorageSync('baseFormData')
											console.log(res)
											uni.showToast({
												title: '支付失败'
											})
										}
									});
								});
								this.$wx.error(function(res) {
									console.log(res, "失败信息3");
								});
							} else {
								uni.showToast({
									title: res.data.msg
								})
							}
						})
					} else {
						console.log('不是微信浏览器')
					}
				} else {
					uni.showToast({
						title: '请先添加交易凭证再进行融资申请',
						icon: 'none'
					});
				}
				// 跳转页
				// if (this.baseFormData.productName == '酒易贷') {
				// 	uni.redirectTo({
				// 		url: '/pages/login/jdLogin'
				// 	})
				// } else if (this.baseFormData.productName == '酒新贷') {
				// 	uni.redirectTo({
				// 		url: '/pages/limit/qrCode'
				// 	})
				// }
			},
			getPayResult() {
				let opt = {
					url: 'yeepay/payResult/' + this.baseFormData.salesOrderNo,
					method: 'GET'
				};
				this.$http.httpTokenRequest(opt).then(res => {
					if (res.data.data == true) {
						console.log('支付成功')
						if (this.baseFormData.productName == '酒易贷') {
							uni.navigateTo({
								url: '/pages/login/jdLogin'
							})
						} else {
							uni.navigateTo({
								url: '/pages/limit/qrCode'
							})
						}
					} else {
						console.log('支付失败')
					}
				})
			},
			financingApply() {
				// 提交融资申请
				let opt = {
					url: 'baoli/finCreditBill',
					method: 'POST'
				};
				this.$http.httpTokenRequest(opt, this.baseFormData).then(res => {
					if (res.data.code == 200) {
						uni.showToast({
							title: res.data.msg,
							icon: 'success',
							duration: 1500
						});
					} else {
						uni.showToast({
							title: res.data.msg,
							icon: 'error',
							duration: 1500
						});
					}
				})
			},
			onSuccess(res) {
				console.log('上传成功回调', res);
				this.fileList.push({
					fileName: res.fileName,
					fileId: res.data.data
				});
				console.log(JSON.stringify(this.fileList))
			}
		}
	}
</script>

<style>
	page {
		background: #f4f4f4;
	}

	.topStep {
		width: 100%;
		/* height: 300rpx; */
		background: #fff;
	}

	.centerBoxtitle {
		font-size: 35rpx;
		color: #000000;
		font-weight: bold;
		margin: 28rpx;

	}

	.numberBox {
		height: 170rpx;
		width: 220rpx;
		text-align: center;
	}

	.numBox {
		/* display: flex; */
		margin-top: 40rpx;
		text-align: center;
	}

	.colorBar {
		height: 40rpx;
		width: 3rpx;
		background: #9d9d9d;
		margin-top: 60rpx;
	}

	.example {
		padding: 20rpx;
		background: #fff;
	}

	.bottomBox {
		position: fixed;
		width: 100%;
		bottom: 20rpx;
		/* margin-bottom: 20rpx; */
		/* z-index: 1000; */
	}

	.buttonBox {
		width: 100%;
		margin: 0 auto;
		display: flex;
		justify-content: space-around;

		// margin-top: 200rpx;
	}

	.button_fix {
		width: 90%;
		height: 70rpx;
		// margin: 0 auto;
		color: #FFFFFF;
		background: #2749C8;
		font-weight: bold;
		letter-spacing: 5rpx;
		font-size: 28rpx;
		line-height: 70rpx;
	}
</style>